#!/usr/bin/env perl
# $Id: ntp.pl 70fe0286d122 2013/07/17 05:39:39 pgurumur $
# Copyright (c) 2013 Prabhu Gurumurthy <pgurumur@gmail.com>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
# File ntp.pl generated on Tuesday June 18, 2013 @22:34:13 PDT
#
# __version__  = "$Revision: 70fe0286d122 $"
# __author__   = "$Author: pgurumur $"
# __modified__ = "$Date: 2013-07-17 05:39:39Z $"
#
use strict;
use IO::Socket;
use Time::HiRes qw(time);
use Getopt::Long;
use Socket qw( SOCK_STREAM );
use Socket::GetAddrInfo qw( getaddrinfo getnameinfo );

Getopt::Long::Configure("default", "bundling");
push my @prog, split(/\//, $0);
my $program = $prog[$#prog];

my $arg = int(scalar(@ARGV));
my %options = ();
my $verbose = 0;

sub ntp_connect {
   my ($name, $port, $type) = @_;
   my $sock = undef;

   if (defined($name) and defined($port) and defined($type)) {
      my %hints = (socktype => $type);
      my ($err, @res) = getaddrinfo($name, $port, \%hints);
      die "Cannot resolve name - $err" if $err;
      foreach my $ai ( @res ) {
         my $newsock = IO::Socket->new();
         $newsock->socket($ai->{family}, $ai->{socktype},
            $ai->{protocol}) or next;
         $newsock->connect($ai->{addr}) or next;
         $sock = $newsock;
         last;
      }
   }

   if (defined($sock)) {
      my ($err, $host, $service) = getnameinfo($sock->peername);
      printf("connected to %s: %s\n", $host, $server) if !$err && $verbose;
   }
   else {
      die "Cannot connect to $name on $port";
   }

   return $sock;
}

sub main {
   GetOptions(\%options, "help|?", "server|s=s", "client|c=s",
      "port|p=i", "verbose|v") or usage();
   usage() if $options{help};
   $verbose = 1 if $options{verbose};
   my $port = defined($options{port}) ? $options{port} : 123;
   

   if (defined($server) and defined($client)) {
      my $server = ntp_connect($server, $port);
      my $client = ntp_connect($server, $port);
